package com.jeeplus.modules.monitor.task;

import com.jeeplus.modules.api.enums.OrderStateEnum;
import com.jeeplus.modules.userorder.entity.UserOrder;
import com.jeeplus.modules.userorder.service.UserOrderService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;

import com.jeeplus.modules.monitor.entity.Task;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Slf4j
@DisallowConcurrentExecution
public class TestTask extends Task {

    @Autowired
    private UserOrderService userOrderService;

    SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void run() {
        // 查询待支付的订单
        UserOrder userOrder = new UserOrder();
        userOrder.setOrderState("1");
        userOrder.setDataScope(" and now() >= SUBDATE(a.create_date,interval -10 minute)");
        List<UserOrder> list = userOrderService.findList(userOrder);
        for (UserOrder order : list) {
            order.setOrderState(OrderStateEnum.CANCEL_PAY.getCode());
            userOrderService.save(order);
        }
        log.info("执行超时订单取消操作");
        // 修改超时的订单状态
        UserOrder userOrder1 = new UserOrder();
        userOrder1.setDataScope(" and a.order_state in ('2')");
        List<UserOrder> list1 = userOrderService.findList(userOrder1);
        for (UserOrder order : list1) {
            // 判断是否过期
            long now = Long.parseLong(sdf.format(new Date()));
            long end = Long.parseLong(order.getEndTime().replace(":", ""));
            if (sdf1.format(new Date()).compareTo(order.getUseDate()) > 0 || ((sdf1.format(new Date()).compareTo(order.getUseDate()) == 0 && end < now))) {
                order.setOrderState(OrderStateEnum.OUT_OF_DATE.getCode());
                order.setOutDate(new Date());
                userOrderService.save(order);
            }
        }
        log.info("执行超时订单过期操作");
    }
}
